// pages/signed_list/signed_list.js
const util = require('../../utils/util.js');
const request = require('../../utils/promise.js');
Page({
  /**
   * 页面的初始数据
   */
  data: {
    page: 0,
    pageSize: 18,
    signedArr: [],
    userInfo: null,  // 用于判断用户是否可以查看其他人的详细信息
    currTap: 0,
    markers: [
      // {year: 2022, month: 3, day: 1, type: 'corner', mark: '', color: ''},
      // {year: 2022, month: 3, day: 2, type: 'schedule', mark: '', color: '', bgColor: ''},
      // {year: 2022, month: 3, day: 3, type: 'holiday', mark: '', color: '', bgColor: ''}
    ],
    yearMonth: null,  // 当前日历年月 yearMonth
    pickerDate: '',
    year: null,
    month: null,
    day: null,
    canISign: false,
    signedTotal: 0,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.reqCurrUserInfo(); // 获取用户信息并判断当天是否已签到
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (this.data.currTap==1) {
      this.reqSignedDataList();  // 列表数据
    }
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    if (this.data.currTap==0) {
      this.reqHasSignedData();  // 日历数据
    } else {
      this.setData({
        page: 0,
        signedArr: []
      })
      this.reqSignedDataList();
    }
    this.reqCurrUserInfo();
    wx.stopPullDownRefresh();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if (this.data.currTap==1) {
      this.reqSignedDataList();  // 上拉加载, 请求列表数据
    }
  },

  /**
   * 页面被用户分享时执行
   */
  onShareAppMessage() {
    return {
      title: '打卡'
    }
  },

  /**
   * 分享到朋友圈
   */
  onShareTimeline() {
    return {
      title: '打卡'
    }
  },

  /**
   * 加载当前用户信息
   */
  reqCurrUserInfo() {
    request.GET('/sign/user/hasSignedInfo', {userId: wx.getStorageSync('userId')}).then(res => {
      // console.log(res) canISign: res.data.canISign
      if (res.data.resCode==200) {
        this.setData({
          userInfo: res.data.userInfo? res.data.userInfo: null
        })
      } else {
        wx.showToast({
          title: '检查是否签到异常',
          icon: 'none'
        })
      }
    })
  },

  /**
   * 加载签到记录
   */
  reqSignedDataList() {
    request.GET('/sign/pageList', {page: this.data.page, pageSize: this.data.pageSize}).then(res => {
      // console.log(res)
      if (res.data.resCode==200) {
        let currPage = this.data.page;
        if (res.data.signArrList.length!=0) {
          currPage++;
        }
        let tempArr = this.data.signedArr;
        tempArr = tempArr.concat(res.data.signArrList);

        this.setData({
          page: currPage,
          signedArr: tempArr
        })
      } else {
        wx.showToast({
          title: '加载异常',
          icon: 'error',
          duration: 1500
        })
      }
    })
  },

  /**
   * 点击查看打卡列表详情
   */
  clickViewSignedDetail(e) {

    let canIView = false;
    let content = '等级限制, 无法查看该社员信息';

    const vip = e.currentTarget.dataset.vip;
    const userId = e.currentTarget.dataset.userid;
    if (this.data.userInfo) {
      if (this.data.userInfo['id']==userId) {
        canIView = true;
      } else {
        if (this.data.userInfo['vip']!=0) {
          if (this.data.userInfo['vip']==100) {
            canIView = true;  // 决策社员允许看所有人的
          } else {
            if (vip!=0) {  // 限制普通社员不能看普通用户
              canIView = true;
            } else {
              content = '社员只能查看其他社员信息，不能查看普通成员信息';
            }
          }
        } else {
          content = '成为社员，才能查看其他社员的信息';
        }
      }
    } else { 
      content = '您尚未登录, 无法查看该社员信息';
    }

    if (!canIView) {
      wx.showModal({
        title: '温馨提示',
        content: content,
        showCancel: false
      })
      return;
    }

    wx.navigateTo({
      url: '/pages/membership_detail/membership_detail?userId='+ e.currentTarget.dataset.userid,
    })
  },

  /**
   * 点击 tab 切换展示
   */
  clickSwiperTap(e) {
    this.setData({
      currTap: e.currentTarget.dataset.curr
    })
  },

  /**
   * 滚动切换 swiper
   */
  swiperChange(e) {
    this.setData({
      currTap: e.detail.current
    })
    if (this.data.page==0) {
      this.reqSignedDataList();
    }
  },

  /**
   * 请求当前月份已签到的数据
   */
  reqHasSignedData() {
    const param = {
      userId: wx.getStorageSync('userId'), year: this.data.year, month: this.data.month
    }
    request.GET('/sign/calDates', param).then(res => {
      if (res.data.resCode==200) {
        this.setData({
          markers: res.data.markersDate
        })
        // 重新设置标记模板
        this.calendar = this.selectComponent('#calendar');
        this.calendar.setMarkers(this.data.markers);
      }
    })
  },

  /**
   * 日历组件加载完成, 设置签到记录
   */
  handleCalendarLoad({detail}) {
    // console.log('calendar-load', detail)
    const yearMonth = detail.date.year +'-'+ (detail.date.month>=10? detail.date.month: '0'+ detail.date.month);
    this.setData({
      yearMonth: yearMonth,
      pickerDate: yearMonth +'-'+ (detail.date.day>=10? detail.date.day: '0'+ detail.date.day),
      year: detail.date.year,
      month: detail.date.month,
      day: detail.date.day
    })
    this.reqHasSignedData();
  },

  /**
   * 日期选择改变
   */
  handleCalendarDateChange({detail}) {
    // console.log(detail)
    let isLoad = false;

    // 年月份不相等, 重新获取数据
    const currDate = detail.date.year +'-'+ (detail.date.month>=10? detail.date.month: '0'+ detail.date.month);
    if (this.data.yearMonth && this.data.yearMonth!=currDate) {
      isLoad = true;
    }

    // 当前选择日期是否相同 (yyyy-MM-dd)
    let recount = false;
    const currPickDate = currDate +'-'+ (detail.date.day>=10? detail.date.day: '0'+ detail.date.day);
    if (currPickDate!=this.data.pickerDate) {
      recount = true;
    }
    
    // 是否显示打卡按钮
    let canISign = false;
    const today = util.formatDate(new Date());
    if (currPickDate==today) {
      canISign = true;
    }
    
    this.setData({
      yearMonth: currDate,
      pickerDate: currPickDate,
      year: detail.date.year,
      month: detail.date.month,
      day: detail.date.day,
      canISign: canISign
    })

    if (isLoad) {
      this.reqHasSignedData();
    }
    
    // 统计当前选择的日期打卡的总人数
    if (recount) {
      this.reqSignedTotalCount();
    }
  },

  /**
   * 获取签到总人数的统计
   */
  reqSignedTotalCount() {
    request.GET('/sign/signedTotal/date', {dateStr: this.data.pickerDate}).then(res => {
      // console.log(res)
      if (res.data.resCode==200) {
        this.setData({
          signedTotal: res.data.signedTotal
        })
      }
    })
  },

  /**
   * 保存打卡 (只能打卡当前日期)
   */
  clickSaveSigned() {

    // 检查用户是否登录
    if (!this.data.userInfo) {
      wx.showModal({
        title: '温馨提示',
        content: '您还没有登录, 无法签到',
        showCancel: false,
      })
      return;
    }
    
    // yyyy-MM-dd, 截取年月日
    const today = util.formatDate(new Date());
    const year = today.substring(0, 4);
    const month = parseInt(today.substring(5, 7));
    const day = parseInt(today.substring(8));

    wx.showToast({
      title: '打卡中...',
      icon: 'loading',
      duration: 300000,
      mask: true
    })

    const param = {
      userId: wx.getStorageSync('userId'), dateStr: today, 
      year: year, month: month, day: day
    }
    request.GET('/sign/saveWorkSign', param).then(res => {
      // console.log(res)
      if (res.data.resCode==200) {
        wx.showToast({
          title: '打卡成功',
          icon: 'success'
        })
        // this.setData({
        //   canISign: false
        // })
        this.reqHasSignedData();
        this.reqSignedTotalCount();
      } else if (res.data.resCode==201) {
        wx.showToast({
          title: '您今天已打卡, 请勿重复操作',
          icon: 'none',
        })
      } else {
        wx.showToast({
          title: '打卡异常',
          icon: 'error',
        })
      }
    })
  },
  
})